/**
 * 负责注册全局需要轮训的事件及统一业务处理
 */

import Api from "@/api/api-declare";
import PD from ".";
import appRunTimer from "../class/app-run-tImer";
import Store from "@/store";
import { ACCOUNT_STATUS } from "../enum/pd-enum";
import { APP_ROUTES } from "../enum/app-routes";
import { Token } from "./token";
import locationMgr from "../class/location-mgr";
import { UniHelp } from "./uni-help";
import voiceMgr from "../class/voiceMgr";

export default function loopEventRegister() {
	drvierQueryAcceptOrders();
	driverUploadLocation();
	driverWarnMsgCheck();
}

/**
 * 司机端-轮训是否有需要接的订单
 * 该轮训为应用内轮训
 * 订单来源自车队派单、应用内新订单通知
 */
function drvierQueryAcceptOrders() {
	if (!PD.AppDeclare.isDriverMini()) return;
	appRunTimer.on('driver-checkHasAcceptOrders', {
		interval: Number(import.meta.env.VITE_QUERY_ACCEPT_ORDERS_DUTACTION),
		handler() {
			if (UniHelp.getCurrentPageIns()?.route === APP_ROUTES.newOrders) return;
			Api.ApiOrder.checkBeingAccept().then(res => {
				if (res.length) {
					voiceMgr.play('newOrderNotice');
					UniHelp.navTo(APP_ROUTES.newOrders);
				};
			});
		},
	});
};

/**
 * 司机端-轮训上传司机坐标
 */
function driverUploadLocation() {
	if (!PD.AppDeclare.isDriverMini()) return;
	appRunTimer.on('driver-uploadPos', {
		interval: Number(import.meta.env.VITE_POS_SUBMIT_DURACTION),
		async handler() {
			//没有token，不处理
			if (!Token.getToken()) return;
			const hasBackgroundPermission = await PD.WxHelp.getPermission('scope.userLocationBackground');
			const hasLocationPermission = await PD.WxHelp.getPermission('scope.userLocation');
			//如果两个权限都没有
			if (!hasLocationPermission && !hasBackgroundPermission) return;
			let location = {
				latitude : 0,
				longitude : 0
			};
			if (hasLocationPermission && !locationMgr.isInBackground) {
				try {
					const { latitude, longitude } = await locationMgr.getLocation();
					location.latitude = latitude;
					location.longitude = longitude;
				} catch (err) {
					console.error('upload2server error:', err);
				};
			};
			if (locationMgr.isInBackground && locationMgr.location.latitude && locationMgr.location.latitude) {
				location = locationMgr.location;
			};
			if (!location.latitude || !location.longitude) return;
			Api.ApiLocation.driverLocationUpload({
				latitude : location.latitude,
				longitude : location.longitude,
				schedule_id: PD.Storage.get('current_schedule_id') || 0
			});
		},
	});
};

/**
 * 司机端-查询是否有警告信息
 * 业务来源：后台-运力管理-账户处罚-警告
 */
function driverWarnMsgCheck() {
	if (!PD.AppDeclare.isDriverMini()) return;
	appRunTimer.on('driver-check-warn-msg', {
		interval: Number(import.meta.env.VITE_DRIVER_CHECK_WARN_MSG_DURACTION),
		handler() {
			Api.ApiDriverUser.checkHasWarnMsg({
				showErrorModal: false,
			}).then(res => {
				if (res && res.content) { //有警告信息，前往账户异常承接页统一处理
					Store.user().accountErrorData = { //数据入缓存
						status: ACCOUNT_STATUS.warn,
						reason: res.content,
						freeze_days: 0,
						freeze_time: 0
					};
					PD.UniHelp.navTo(APP_ROUTES.accountError);
				};
			});
		}
	});
};